<?php
/**
 * 生成静态HTML缓存
 *
 * @filesource ob_html_cache.func.php
 * @package DsCache
 * @subpackage ob_html_cache 
 * @version $id: 0.3, utf8, Fri Dec 18 09:36:44 CST 2009
 * @author LD King <kldscs[at]gmail.com>
 * @copyright Copyleft (D.) 2007 - 2009 MiFunny China Inc.
 * @link http://mifunny.info/
 * @example 
 *   
 */
//error_reporting(E_ALL & ~(E_STRICT | E_NOTICE));
//error_reporting(E_ALL | E_STRICT);

//判断配置是否存在...
function ob_cache( $id=null ){
	global $_config;
	if( empty($_config['DsCache']) ){
		$_config['DsCache'] = array(
			'cache_type'=> 'htmlfile', //生成静态HTML(必须)
			'cache_dir' => '/tmp', //缓存目录(必须)
			'cache_dir_umask'   => 0777,
			'life_time' => 900, //全局缓存时间 900s.
			'gizp' => true, //使用gzip压缩输出
			'gzip_level' => 9, //压缩等级为9
		);
	}
	
	//生成 Cache 的文件名
	if ( empty($id) ) {
		$key = trim($_SERVER["REQUEST_URI"], '/').'.html';
	}else $key = $id;
	
	//判断是否可以压缩
	if ($_config['DsCache']['gizp'] == true){
		$_config['DsCache']['gizp'] = false;
		if (extension_loaded('zlib')){
			if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) AND strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE){
				$_config['DsCache']['gizp'] = true;//ob_start('ob_gzhandler');
				//$_config['DsCache']['gzip_level'] = 
				//  is_numeric($_config['DsCache']['gzip_level']) ? $_config['DsCache']['gzip_level'] : 9;
			}
		}
	}
	if ( $_config['DsCache']['gizp'] ){
		ob_start('ob_gzhandler');
	}else ob_start();
	
	//缓存单页(⊙o⊙)哦！
	if ( $buffer = Cache::get($key) ) {
		echo $buffer.'<!-- DsCached -->';
		ob_end_flush(); exit; //这么做不太好吧, 集成在视图不错.
	}else{
		register_shutdown_function('ob_cachehandler', $key);
	}
}//END func ob_cache

// 根据输出, 生成缓存
function ob_cachehandler($key) { 
	$buffer = ob_get_contents(); 
	
	if (!empty($buffer)) {
		//echo "<br />\t\n<b>key</b>: ".$key;
		//echo "<br />\t\n<b>buffer</b>: ".$buffer;
		Cache::set($key, $buffer);
	}
	ob_end_flush();
}//END func ob_cachehandler

?>
